package com.lcache.core.service.impl;

import com.lcache.core.service.Level3DBStore;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LocalTableStore implements Level3DBStore {

    private static final String FILE_PATH = "D:/local_kv_store.txt";
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 本地持久化缓存读取
     */
    @Override
    public Object get(String key) {
        lock.readLock().lock();
        try {
            List<String> lines = Files.readAllLines(Paths.get(FILE_PATH));
            for (String line : lines) {
                if (line.startsWith(key + "=")) {
                    return line.substring(key.length() + 1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return null;
    }

    /**
     * 本地持久化缓存写入
     */
    @Override
    public void set(String key, Object value) {
        lock.writeLock().lock();
        try {
            File file = new File(FILE_PATH);
            List<String> lines = file.exists() ? Files.readAllLines(file.toPath()) : new ArrayList<>();
            boolean updated = false;

            for (int i = 0; i < lines.size(); i++) {
                if (lines.get(i).startsWith(key + "=")) {
                    lines.set(i, key + "=" + value);
                    updated = true;
                    break;
                }
            }

            if (!updated) {
                lines.add(key + "=" + value);
            }

            Files.write(file.toPath(), lines);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 本地持久化缓存删除
     */
    @Override
    public void delete(String key) {
        lock.writeLock().lock();
        try {
            File file = new File(FILE_PATH);
            if (!file.exists()) return;

            List<String> lines = Files.readAllLines(file.toPath());
            lines.removeIf(line -> line.startsWith(key + "="));
            Files.write(file.toPath(), lines);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
}
